package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.domain.enumeration.BannerStatus;
import cn.com.connext.scrm.domain.master.BannerList;
import cn.com.connext.scrm.service.BannerListService;
import cn.com.connext.scrm.service.dto.BannerListDTO;
import cn.com.connext.scrm.service.mapper.BannerListMapper;
import com.codahale.metrics.annotation.Timed;
import com.connext.common.exception.ErrorCode;
import com.connext.common.exception.ServiceException;
import com.connext.common.web.rest.BaseResource;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URISyntaxException;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeoutException;

/**
 * Created by yuanyajun on 2018/7/23.
 */
@RestController
@RequestMapping("/api/bannerlist")
public class BannerListResource extends BaseResource {
    private final Logger log = LoggerFactory.getLogger(BannerListResource.class);

    @Autowired
    private BannerListMapper bannerListMapper;

    @Autowired
    private BannerListService bannerListService;

    public BannerListResource() throws TimeoutException {
        super("BrowseRecord");
    }

    @GetMapping("/getBannerListCondition")
    @Timed
    @ApiOperation(value = "获取轮播图列表", tags = {"轮播图列表"}, notes = "获取轮播图列表")
    public ResponseEntity<Page<BannerListDTO>> getBannerListCondition(@ApiParam Pageable pageable,
                                                                      @RequestParam(value = "name", required = false) String name,
                                                                      @RequestParam(value = "redirectType", required = false) String redirectType,
                                                                      @RequestParam(required = false) Integer status, @RequestParam(value = "type", required = false) Integer type
    ) throws URISyntaxException {
        BannerListDTO bannerListDTO = new BannerListDTO();
        bannerListDTO.setName(name);
        if (StringUtils.isNotEmpty(redirectType)) {
            bannerListDTO.setRedirectType(redirectType);
        }
        if (status != null) {
            bannerListDTO.setStatus(status);
        }
        if (type != null){
            bannerListDTO.setType(type);
        }
        bannerListDTO.setDeleteFlag(false);
        Page<BannerListDTO> page = bannerListService.getAllBannerList(pageable, bannerListDTO);
        return pagedResponse(page);
    }

    @PostMapping("/create")
    @Timed
    @ApiOperation(value = "添加轮播图", tags = {"轮播图列表"}, notes = "添加轮播图")
    public ResponseEntity<BannerListDTO> create(@RequestBody BannerListDTO bannerListDTO) throws URISyntaxException {
        log.debug("REST to create BannerList:{}", bannerListDTO);
        if (StringUtils.isNotEmpty(bannerListDTO.getId())) {
            throw new ServiceException(ErrorCode.ERROR_ID_EXISTS);
        }
        BannerList bannerList = bannerListMapper.toEntity(bannerListDTO);
        bannerList.setStatus(BannerStatus.DISABLED.getCode());
        bannerList.setDeleteFlag(false);
        bannerList.setCreateTime(ZonedDateTime.now());
        BannerListDTO result = bannerListService.saveBannerList(bannerList);
        return createSuccess(result);
    }

    @GetMapping("/getBannerList/{id}")
    @Timed
    @ApiOperation(value = "获取轮播图信息", tags = {"轮播图列表"}, notes = "获取轮播图信息")
    public ResponseEntity<BannerListDTO> getBannerListById(@PathVariable String id) {
        log.debug("REST request to get BannerList : {}", id);
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ErrorCode.ERROR_ID_NOT_EXISTS);
        }
        BannerListDTO bannerListDTO = bannerListService.findOneDTO(id);
        return entityResponse(Optional.ofNullable(bannerListDTO));
    }

    @GetMapping("/getBannerListByStatus")
    @Timed
    @ApiOperation(value = "获取轮播图信息(小程序)", tags = {"轮播图列表(小程序)"}, notes = "获取轮播图信息(小程序)")
    public ResponseEntity<BannerListDTO> getBannerListByStatus(Integer type) {
        log.debug("REST request to get BannerListByStatus : {}");
        List<BannerListDTO> bannerListDTO = bannerListService.getBannerListByStatus(type);
        return entityResponse(Optional.ofNullable(bannerListDTO));
    }

    @PutMapping("/update")
    @Timed
    @ApiOperation(value = "修改轮播图", tags = {"轮播图列表"}, notes = "修改轮播图")
    public ResponseEntity<BannerListDTO> update(@RequestBody BannerListDTO bannerListDTO) throws URISyntaxException {
        log.debug("REST to update BannerList:{}", bannerListDTO);
        if (StringUtils.isEmpty(bannerListDTO.getId())) {
            throw new ServiceException(ErrorCode.ERROR_ID_EXISTS);
        }
        BannerList bannerList = bannerListMapper.toEntity(bannerListDTO);
        BannerListDTO result = bannerListService.updateBannerListById(bannerList);
        return createSuccess(result);
    }

    @PostMapping("/changeStatus/{id}")
    @Timed
    @ApiOperation(value = "更改轮播图状态", tags = {"轮播图列表"}, notes = "更改轮播图状态")
    public ResponseEntity changeBannerStatus(@PathVariable String id) {
        log.debug("REST request to change Banner status: {}", id);
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ErrorCode.ERROR_ID_NOT_EXISTS);
        }
        bannerListService.changeBannerStatus(id);
        return deleteSuccess();
    }

    @DeleteMapping("/delete/{id}")
    @Timed
    @ApiOperation(value = "删除轮播图", tags = {"轮播图列表"}, notes = "删除轮播图")
    public ResponseEntity deleteBanner(@PathVariable String id) {
        log.debug("REST request to delete Banner : {}", id);
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ErrorCode.ERROR_ID_NOT_EXISTS);
        }
        bannerListService.deleteBanner(id);
        return deleteSuccess();
    }

    @PostMapping("removeCache")
    @Timed
    @ApiOperation(value = "删除轮播图缓存", tags = {"轮播图列表"}, notes = "删除轮播图缓存")
    public ResponseEntity removeCache(){
        bannerListService.removeCache();
        return successResponse();
    }
}
